package com.evan.wj.controller;

import com.evan.wj.pojo.Character;
import com.evan.wj.pojo.QueryDTO;
import com.evan.wj.service.CharacterService;
import com.evan.wj.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;


@Api(tags = "CharactersController - 角色controller")
@RestController
public class CharactersController {
    @Autowired
    CharacterService characterService;

    @GetMapping("/api/characters")
    public List<Character> list() throws Exception {
        return characterService.list();
    }

    @PostMapping("/api/characters")
    public Character addOrUpdate(@RequestBody Character character) throws Exception {
        characterService.addOrUpdate(character);
        return character;
    }

    @PostMapping("/api/deleteC")
    public void delete(@RequestBody Character character) throws Exception {
        characterService.deleteById(character.getId());
    }

    @ApiOperation(value = "列表查询角色信息", notes = "...")
    @PostMapping("/api/careers")
    public List<Character> listfindByScreen(@RequestBody QueryDTO queryDTO) throws Exception {
        System.out.println(queryDTO);
        return null;

    }

    @CrossOrigin
    @GetMapping("/api/searchC")
    public List<Character> searchResult(@RequestParam("keywords") String keywords) {
        // 关键词为空时查询出所有书籍
        if ("".equals(keywords)) {
            return characterService.list();
        } else {
            return characterService.Search(keywords);
        }
    }
    @CrossOrigin
    @PostMapping("api/coversC")
    public String coversUpload(MultipartFile file) throws Exception {
        String folder = "D:/workspace/img";
        File imageFolder = new File(folder);
        File f = new File(imageFolder, StringUtils.getRandomString(6) + file.getOriginalFilename()
                .substring(file.getOriginalFilename().length() - 4));
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8443/api/file/" + f.getName();
            return imgURL;
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }


}

